import { Component, NgZone } from '@angular/core';
import { NavController, NavParams, LoadingController, PopoverController } from 'ionic-angular';
import { GLCatalogProvider, GLItem, GLContent } from '../../app/classes/GLCatalog';
import MenuPage from '../../app/menu.component';

@Component({
	selector: 'page-home',
	templateUrl: 'home.html'
})
export class HomePage {
	item: GLItem;
	private paragraphs: boolean;
	getParagraphs() {
		return "paragraphs" in localStorage;
	}
	constructor(private catalogProvider: GLCatalogProvider, private zone: NgZone, private navCtl: NavController, private params: NavParams, private loadingCtl: LoadingController, private popoverCtl: PopoverController) {
		this.paragraphs = this.getParagraphs();
		setTimeout(() => {
			(() => {
				if("item" in params.data) {
					let item = params.get('item');
					return Promise.resolve(item);
				}
				var uri = params.get('uri');
				if(!uri) {
					uri = "/";
				}
				return catalogProvider.getCatalog().then((catalog) => catalog.getItem(uri));
			})().then((item) => {
				this.zone.run(() => {
					this.item = item;
					console.log(item);
				});
			}).catch(console.error);
		});
	}
	openItem(subitem: GLItem) {
		let loading = this.loadingCtl.create();
		loading.present();
		this.catalogProvider.getCatalog().then((catalog) => {
			return subitem.getItem(catalog);
		})
		.then((item) => {
			this.navCtl.push(HomePage, {item: item});
		})
		.catch(console.error)
		.then(() => loading.dismiss());
	}
	openReferences(focus: string) {
		let loading = this.loadingCtl.create();
		loading.present();
		let dest = "/refs"+this.item.uri;
		this.catalogProvider.getCatalog().then((catalog) => catalog.getItem(dest))
		.then((item: GLContent) => {
			item.focus = "#note"+focus;
			this.navCtl.push(HomePage, {item: item, focus: focus});
		})
		.catch(console.error)
		.then(() => loading.dismiss());
	}
	openURI(uri: string) {
		let loading = this.loadingCtl.create();
		loading.present();
		this.catalogProvider.getCatalog().then((catalog) => catalog.getItem(uri))
		.then((item) => this.navCtl.push(HomePage, {item: item}))
		.catch(console.error)
		.then(() => loading.dismiss());
	}
	openMenu(event: Event) {
		this.popoverCtl.create(MenuPage, {
			updateParagraphs: () => {
				this.zone.run(() => {
					this.paragraphs = this.getParagraphs();
				});
			}
		}).present({ev:event});
	}
}
